package com.cicadasmall.redis.lock;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 基于 Redisson的lock
 *
 * @author Jin
 */
@Slf4j
@AllArgsConstructor
public class RedisLock {

    private RedissonClient redissonClient;


    /**
     * 根据Key 和超时时间加锁
     *
     * @param key
     * @param expire
     * @return
     */
    public boolean lock(String key, long expire) {
        if (StringUtils.isBlank(key)) {
            return false;
        }

        try {
            RLock rLock = redissonClient.getLock(key + "_lock");
            //不做任何等待,抢不到就返回false
            if (rLock.tryLock(-1, expire, TimeUnit.MILLISECONDS)) {
                return true;
            }
            return false;
        } catch (InterruptedException e) {
            log.error("locking error", e);
            return false;
        }


    }

    /**
     * 根据Key解锁
     *
     * @param key
     */
    public void unlock(String key) {

        if (StringUtils.isBlank(key)) {
            return;
        }
        try {
            RLock rLock = redissonClient.getLock(key + "_lock");
            if (rLock.isLocked()) {
                rLock.unlock();
            }
        } catch (Throwable e) {
            log.error("unlock error", e);
        }
    }

}
